package com.foreknow.demo141;

import java.sql.*;

/**
 * @author shkstart
 * @create 2021-08-03 15:10
 */
public class DBUtil {
    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;


    /**
     * 连接数据库的方法
     */

    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/basic5?useSSL=false&serverTimezone=UTC";
        conn = DriverManager.getConnection(url, "root", "123456");
        return conn;
    }

    /**
     * 查询操作
     */
    public ResultSet Query(String sql, Object... valuses) throws SQLException {
        //3.获取PreParedStatement对象用于执行动态sql
        pstmt = conn.prepareStatement(sql);
        //将sql中的？ 替换为具体的值
        for (int i = 0; i < valuses.length; i++) {
            pstmt.setObject(i + 1, valuses[i]);  //将地i+1个问号替换成数组中具体的值
        }

        ResultSet rs = pstmt.executeQuery();

        return rs;

    }

}
